<?php
/**
 * Created by George Antoniou.
 * Date: 7/6/14
 * Time: 7:24 PM
 * add.php
 * To change this template use File | Settings | File Templates.
 */

if(!isset($_GET['submit'])){
    $SKU=uniqid('SKU');
    ?>
    <script type="text/javascript" src="sources/validate.min.js"></script>
    <form name="addForm" id="addForm" class="form-horizontal" method="get" action="index.php?action=add" onsubmit="return validate()">
        <fieldset>

            <!-- Form Name -->
            <legend>Add Product</legend>
            <input type="hidden" value="add" name="action" />
            <input type="hidden" value="<?= $SKU ?>" name="SKU" />
            <!-- Text input-->
            <div class="control-group">
                <label class="control-label" for="SKU">SKU</label>
                <div class="controls">
                    <input id="SKU" disabled name="SKU" type="text"  value= "<?= $SKU ?>" placeholder="placeholder" class="input-medium">
                    <p class="help-block">Autogenerated SKU Number</p>
                </div>
            </div>

            <!-- Text input-->
            <div class="control-group">
                <label class="control-label" for="name">Product Name</label>
                <div class="controls">
                    <input id="name" name="name" type="text" placeholder="" class="input-medium" required="" onBlur="validateEmpty(this,'onomaR')">
                    <p class="help-block">Product Name <div id="onomaR" style="visibility:hidden">This field is Required</div></p>

                </div>
            </div>

            <!-- Textarea -->
            <div class="control-group">
                <label class="control-label" for="description">Product Description</label>
                <div class="controls">
                    <textarea id="description" name="description"  onkeyup="valid(this)" onblur="valid(this)" >default text</textarea>
                    <p><div id="descR" style="visibility:hidden">This field is Required</div></p>
                </div>
            </div>

            <!-- Text input-->
            <div class="control-group">
                <label class="control-label" for="price">Product Price</label>
                <div class="controls">
                    <input id="price" name="price" type="text" placeholder="placeholder" class="input-medium allownumericwithdecimal" required="" onBlur="validateEmpty(this,'priceR')" >
                    <p class="help-block">Product Price <div id="priceR" style="visibility:hidden">This field is Required</div></p>
                </div>
            </div>

            <!-- Select Basic -->
            <div class="control-group">
                <label class="control-label" for="stock">Stock</label>
                <div class="controls">
                    <input id="stock" name="stock" type="text" placeholder="placeholder" class="input-medium" required="" onBlur="validateEmpty(this,'stockR')" onkeypress="return isNumberKey(event)" >
                    <p class="help-block">Only Integer Quantity allowed here<div id="stockR" style="visibility:hidden">This field is Required</div></p>
                </div>
            </div>

            <!-- Select Basic -->
            <div class="control-group">
                <label class="control-label" for="CATID">Category</label>
                <div class="controls">

                    <?php getCats(); ?>

                </div>
            </div>

            <!-- File Button -->
            <div class="control-group">
                <label class="control-label" for="img">select an image</label>
                <div class="controls">
                    <!--<input id="img" name="img" class="input-file" type="file"> -->
                    <select id="img" name="img" class="image-picker">
                        <?php getImages(); ?>
                    </select>
                </div>
            </div>

            <!-- Button -->
            <div class="control-group">
                <label class="control-label" for="submit">Add Product</label>
                <div class="controls">
                    <button id="submit" name="submit" class="btn btn-primary">Add</button>
                </div>
            </div>

        </fieldset>
    </form>
    <script type="text/javascript">
        $("select").imagepicker()//enable picker
        /*
         * Check that fields in form are completed
         */
        function validateEmpty(field,element){
            //alert(element);
            var empty=field.value;
            var elem = document.getElementById(element);
            var elem2=document.getElementById(field.name);
            //alert (elem);
            if (empty==null || empty=="" ) { // empty
                elem.style.color="red";
                elem.style.visibility="visible";
                elem2.style.borderColor="red";

            }else {
                //alert("mpika pio mesa2");
                elem.style.visibility="hidden";
                elem2.style.borderColor="";
            }
        }

        /* Allow only nummbers from 0to9 to be typed in textbox*/

        function isNumberKey(evt) {
            var charCode = (evt.which) ? evt.which : event.keyCode
            if (charCode > 31 && (charCode < 48 || charCode > 57))
                return false;

            return true;
        }

        //allow only numeric values on price
        $(".allownumericwithdecimal").on("keypress keyup blur",function (event) {
            //this.value = this.value.replace(/[^0-9\.]/g,'');
            $(this).val($(this).val().replace(/[^0-9\.]/g,''));
            if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
                event.preventDefault();
            }
        });

        //text area validation
        function valid(f) {
            !(/^[A-z \n &#209; \n &#241; 0-9 \n ]*$/i).test(f.value)?f.value = f.value.replace(/[^A-z \n &#209; \n &#241; \n 0-9 \n ]/ig,''):null;
        }
        //re-validate fields on submit
        function validate(){
            var str = '';
            var div='';
            var error=false;
            var elem = document.getElementById('addForm').elements;
            for(var i = 0; i < elem.length; i++){
                if(elem[i].type=="text"){
                    if( (elem[i].value==null) || (elem[i].value=="") ){
                        error=true;
                        div.style.color="red";
                        //elem[i].style.backgroundColor = "#FFCC00";
                        div.style.visibility="visible";
                        var elem2=document.getElementById(elem[i].name);
                        elem2.style.borderColor="red";
                        //str+=elem[i].name+"   "+elem[i].value +"\n";
                        //str+= div.id +"  \n";
                    }
                    else{
                        //error=false;
                    }

                }

            }
        }

    </script>

<?php
}
else {
    //var_dump($_GET);
    if(isset($_GET['SKU'])&& isset($_GET['name']) && ($_GET['name']!=null) && isset($_GET['price']) && ($_GET['price'])!=null ){
        //echo "1";
        if( isset($_GET['description']) && ($_GET['description']!=null) && isset($_GET['img']) && ($_GET['img'])!=null && isset($_GET['CATID']) && isset($_GET['stock'])){
            //echo "2";    //var_dump($_POST);
            //include "../Core/config.php";
            $SKU=$_GET['SKU'];$name;$price;$description;$img;$cat;$stock;
            $alert=false;
            $errors=array();
            //time for some basic validation
            $name=strip_Characters($_GET['name']);
            $description=strip_Characters($_GET['description']);
            $stock=strip_Characters($_GET['stock']);
            $price=strip_Characters($_GET['price']);
            $cat=strip_Characters($_GET['CATID']);
            $img=$_GET['img'];

            //$price=filter_var($_GET['price'], FILTER_SANITIZE_NUMBER_INT);
           /* if(check_invalid_input(strip_Characters($_GET['name']))  && check_invalid_input(strip_Characters($_GET['stock']))) {

                $errors['name']=check_invalid_input(strip_Characters($_GET['name']));
                $errors['description']=check_invalid_input(strip_Characters($_GET['description']));
                $errors['stock']=check_invalid_input(strip_Characters($_GET['stock']));
                $errors['price']=check_invalid_input(strip_Characters($_GET['price']));
            }else $alert=true;*/

            if($alert==false){
               add($SKU,$name,$price,$description,$img,$cat,$stock);
            }
            else{
                echo "    <div class='alert alert-warning'>
    <strong>OOOPS!</strong> We are sorry, something seemed not to be right with your request.. :(
    </div>"; //var_dump($errors);
                //echo $form;
            }
        } //echo "3";

    }
}

function getCats(){
    $url = 'http://'.HOST.'/'.ROOT.'/Core/RestServices/Product.php/product/category/';
    $client = curl_init($url);
    curl_setopt($client, CURLOPT_RETURNTRANSFER, 1);
    $response = curl_exec($client);
    curl_close($client);
    try{
        //$response='<test>'.$response.'/<test>';
        //echo $response;
        $xml = simplexml_load_string($response);
    }catch(Exception $e) {
        //echo $e->getMessage();
    } //var_dump($xml) ;
    echo'<label class="radio inline" for="radios-0"> None';
    echo'<input type="radio" name="CATID" id="radios-0" value="null" checked = "" >
        </label>';
    foreach($xml->category as $category){
        //$parents[]=(array("id"=>$category->ID, "name"=>$category->cat_name));
        echo'<label class="radio inline" for="radios-0">'.$category->name;
        echo'<input type="radio" name="CATID" id="radios-0" value="'.$category->ID.'" checked = "" >
        </label>';
        //echo '<option value="'.$category->ID.'">'.$category->name.'</option>';
    }
    //return $parents;
}


//var_dump(getImages());

function getImages(){
    $files1 = scandir("../uploads/");
    foreach($files1 as $img) {
        $ext= pathinfo($img, PATHINFO_EXTENSION);
        if($ext!=null){
            //echo $img." ext= ".$ext."     \n";
            //return $img;
            echo "<option  data-img-src='../uploads/".$img."'  value='".$img."' >";
        }
    }
}

function add($SKU,$name,$price,$description,$img,$cat,$stock){
    //send user data to REST service and add user to database
        $url = 'http://'.HOST.'/'.ROOT.'/Core/RestServices/Product.php/product/add/';
        $data = "<productss>
                <product>
                    <SKU>$SKU</SKU>
                    <name>$name</name>
                    <description>$description</description>
                    <category>$cat</category>
                    <price>$price</price>
                    <stock>$stock</stock>
                    <img>$img</img>
                </product>
             </productss>";

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

        $response = curl_exec($ch);

        //debugging stuff..
        /*echo var_dump($response);
        echo var_dump($data);
        echo $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        */
        curl_close($ch);
        try{
            //$response='<test>'.$response.'/<test>';
            //echo $response;
            $xml = simplexml_load_string($response);
        }catch(Exception $e) {
            //echo $e->getMessage();
        }
    if(isset($xml->error)){
        echo "    <div class='alert alert-warning'>
<strong>OOOPS!</strong> We are sorry, $xml->error.. :( Please Try Again...
</div>";
    }
    else{
        //echo var_dump($xml);
        echo "    <div class='alert alert-info'>
<strong>PRoduct Added :)</strong> <pre> You can now edit or delete it! Product SKU: $SKU</pre>
</div>";
    }//var_dump($xml);

 }

